package kr.couponplay.android.activity.deal;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.Category;
import kr.couponplay.android.activity.R;
import kr.couponplay.android.activity.ResourceUtils;
import kr.couponplay.android.activity.TitleBarHelper;
import kr.couponplay.android.activity.TitleBarHelper.TabMenuType;
import kr.couponplay.android.activity.TitleBarHelper.TitleLayout;
import kr.couponplay.android.activity.deal.category.CategoryButtonOnClickListener;
import kr.couponplay.android.activity.deal.category.CategoryHelper;
import kr.couponplay.android.activity.deal.category.CategoryListFragment;
import kr.couponplay.android.activity.deal.list.DealListViewPagerAdapter;
import kr.couponplay.android.activity.deal.menu.SubMenuButton;
import kr.couponplay.android.activity.deal.menu.SubMenuButtonOnClickListener;
import kr.couponplay.android.activity.deal.menu.SubMenuHelper;
import kr.couponplay.android.activity.deal.menu.TopMenuButton;
import kr.couponplay.android.activity.deal.menu.TopMenuButtonOnClickListener;
import kr.couponplay.android.activity.deal.menu.TopMenuHelper;
import kr.couponplay.android.domain.BeanFactory;
import kr.couponplay.android.domain.deal.DealDao;
import kr.couponplay.android.domain.deal.DealListResult;
import kr.couponplay.android.support.AlertUtils;
import kr.couponplay.android.support.DisplayUtils;
import kr.couponplay.android.support.slidingmenu.SlidingMenu;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;

@SuppressLint("HandlerLeak") 
public class DealListActivity extends DealBaseActivity {
	private static final TabMenuType TAB_MENU_TYPE = TabMenuType.MAIN;
	private DealListActivity activity = this;
	private TopMenuButtonOnClickListener topMenuButtonOnClickListener;
	private SubMenuButtonOnClickListener subMenuButtonOnClickListener;

	private CategoryListFragment categoryListFragment;
	
	private ViewPager dealListViewPager;
	private DealListViewPagerAdapter dealListViewPagerAdapter;
	
	private ProgressDialog dataLoadingDialog;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        try {
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.deal_list_activity);
	
	        drawTop();
	        drawSub();
	        drawCategory();
	        drawBody();
	        getDealList();
        } catch (Exception e) {
        	AlertUtils.errorAlert(this, null);
        }
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	TitleBarHelper.setVisibable(TAB_MENU_TYPE);
    }

	private void drawTop() {
		LinearLayout titleLinearLayout = (LinearLayout)LayoutInflater.from(this).inflate(R.layout.deal_title, null);
		topMenuButtonOnClickListener = new TopMenuButtonOnClickListener(this);
		for (Category mainCategory : AppContext.getMainCategories(activity)) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1.0f);
			params.setMargins(0, 0, 0, DisplayUtils.pixelFromDp(activity, 2));
	
			Button topMenuButton = new Button(activity);
			topMenuButton.setText(mainCategory.getName());
			topMenuButton.setTextSize(12);
			topMenuButton.setPadding(0, DisplayUtils.pixelFromDp(activity, 7), 0, DisplayUtils.pixelFromDp(activity, 4));
			topMenuButton.setGravity(Gravity.CENTER);
			topMenuButton.setCompoundDrawablesWithIntrinsicBounds(0, ResourceUtils.getDrawable(mainCategory.getCode()), 0, 0);
			topMenuButton.setCompoundDrawablePadding(DisplayUtils.pixelFromDp(activity, 2));
			topMenuButton.setLayoutParams(params);
			topMenuButton.setOnClickListener(topMenuButtonOnClickListener);
			titleLinearLayout.addView(topMenuButton);
			
			TopMenuHelper.topMenuButtons.add(new TopMenuButton(topMenuButton, mainCategory));
		}
		TitleBarHelper.addTitleLayout(new TitleLayout(titleLinearLayout, TAB_MENU_TYPE));
		TopMenuHelper.selectTopMenuButton(TopMenuHelper.topMenuButtons.get(TopMenuHelper.selectedTopMenuButtonIndex).getButton());
	}
	
	private void drawSub() {
		subMenuButtonOnClickListener = new SubMenuButtonOnClickListener(this);
		
		Button subAllButton = (Button)findViewById(R.id.sub_all_button);
		subAllButton.setOnClickListener(subMenuButtonOnClickListener);
		SubMenuHelper.subMenuButtons.add(new SubMenuButton(subAllButton, SubMenuButton.Type.ALL));
		
		Button subNewButton = (Button)findViewById(R.id.sub_new_button);
		subNewButton.setOnClickListener(subMenuButtonOnClickListener);
		SubMenuHelper.subMenuButtons.add(new SubMenuButton(subNewButton, SubMenuButton.Type.NEW));
		
		Button subEndButton = (Button)findViewById(R.id.sub_end_button);
		subEndButton.setOnClickListener(subMenuButtonOnClickListener);
		SubMenuHelper.subMenuButtons.add(new SubMenuButton(subEndButton, SubMenuButton.Type.END));
		
		Button subFreeButton = (Button)findViewById(R.id.sub_free_button);
		subFreeButton.setOnClickListener(subMenuButtonOnClickListener);
		SubMenuHelper.subMenuButtons.add(new SubMenuButton(subFreeButton, SubMenuButton.Type.FREE));
		
		SubMenuHelper.selectSubMenuButton(SubMenuHelper.selectedSubMenuButtonIndex);
	}
	
	private void drawCategory() {
        Button categoryButton = (Button)findViewById(R.id.category_button);
        categoryButton.setOnClickListener(new CategoryButtonOnClickListener(this));
        
		categoryListFragment = CategoryListFragment.newInstance(this);
		
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.replace(R.id.category_framelayout, categoryListFragment).commit();
		setSlidingActionBarEnabled(false);
		setBehindContentView(R.layout.category_body);
		
		SlidingMenu slidingMenu = getSlidingMenu();
//		slidingMenu.setShadowWidthRes(R.dimen.shadow_width);
//		slidingMenu.setShadowDrawable(R.drawable.shadow);
		slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		slidingMenu.setFadeDegree(0.35f);
		slidingMenu.setTouchModeAbove(SlidingMenu.SLIDING_CONTENT);
	}
	
	private void drawBody() {
        dealListViewPager =(ViewPager)findViewById(R.id.sub_menu_viewpager);
        dealListViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			@Override
			public void onPageSelected(int position) {
				SubMenuHelper.selectSubMenuButton(position);
				if (position == 0) {
					getSlidingMenu().setTouchModeAbove(SlidingMenu.SLIDING_CONTENT);
				} else {
					getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
				}
			}
        });
	}
	
	public void getDealList() {
		dataLoadingDialog = ProgressDialog.show(activity, null, "데이터 수신중입니다.", true, false);
		Thread thread = new Thread(new Runnable() {
            public void run() {
            	Message msg = Message.obtain();
            	try {
	            	int mainCategoryId = CategoryHelper.mainCategoryId;
	        		int subCategoryId = CategoryHelper.subCategoryId;
	        		msg.obj = BeanFactory.getBean(activity.getApplicationContext(), DealDao.class).selectAllDealList(mainCategoryId, subCategoryId, 0);
            	} catch (Exception e) {
            		msg.obj = e;
            	}
            	handler.sendMessage(msg);
            }
        });
        thread.start();
	}
	
	private Handler handler = new Handler() {
	    public void handleMessage(Message msg) {
	    	if (msg.obj instanceof Throwable) {
	    		alert((Exception)msg.obj);
	    		dataLoadingDialog.dismiss();
	    		return;
	    	}
	    	
	    	DealListResult dealListResult = (DealListResult)msg.obj;
		    dealListViewPagerAdapter = new DealListViewPagerAdapter(activity, dealListResult);
	    	dealListViewPagerAdapter.replace();
	    	dealListViewPager.removeAllViews();
		    dealListViewPager.setAdapter(dealListViewPagerAdapter);
		    dealListViewPager.setCurrentItem(0);
		    dataLoadingDialog.dismiss();
	    }
	};
	
    public void alert(Exception exception) {
        AlertUtils.errorAlert(this, exception);
    }

	public CategoryListFragment getCategoryListFragment() {
		return categoryListFragment;
	}

	public ViewPager getDealListViewPager() {
		return dealListViewPager;
	}
}
